// 配置对象
const config = {
    updateInterval: 5000, // 数据更新间隔（毫秒）
    chartOptions: {
        responsive: true,
        animation: {
            duration: 1000,
            easing: 'easeOutQuart'
        },
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    padding: 20,
                    usePointStyle: true,
                    font: {
                        size: 12
                    }
                }
            },
            tooltip: {
                mode: 'index',
                intersect: false,
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                titleColor: '#000',
                bodyColor: '#666',
                borderColor: '#ddd',
                borderWidth: 1,
                padding: 10,
                boxPadding: 4
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    drawBorder: false,
                    color: 'rgba(0,0,0,0.05)'
                },
                ticks: {
                    callback: function(value) {
                        return value + '%';
                    }
                }
            },
            x: {
                grid: {
                    display: false
                },
                ticks: {
                    maxRotation: 0,
                    maxTicksLimit: 8
                }
            }
        },
        elements: {
            line: {
                tension: 0.4
            },
            point: {
                radius: 4,
                hitRadius: 10,
                hoverRadius: 6
            }
        },
        interaction: {
            mode: 'nearest',
            axis: 'x',
            intersect: false
        }
    }
};

// 添加传感器配置
const sensorConfig = {
    depths: [10, 20, 30, 50, 100],
    currentDepth: 10,
    samplingRate: 1000,  // 改为1秒
    dataRetention: 30 // 分钟
};

// 添加分层数据存储
const depthData = {
    10: { moisture: [], waterPotential: [], temperature: [], humidity: [], conductivity: [] },
    20: { moisture: [], waterPotential: [], temperature: [], humidity: [], conductivity: [] },
    30: { moisture: [], waterPotential: [], temperature: [], humidity: [], conductivity: [] },
    50: { moisture: [], waterPotential: [], temperature: [], humidity: [], conductivity: [] },
    100: { moisture: [], waterPotential: [], temperature: [], humidity: [], conductivity: [] }
};

// 实时数据图表初始化
let realTimeChart;
let dayChart;
let profileChart;

// 页面管理
const pages = {
    realtime: 'realtimePage',
    history: 'historyPage',
    profile: 'profilePage',
    settings: 'settingsPage'
};

// 页面标题映射
const pageTitles = {
    realtime: '实时监测',
    history: '历史数据',
    profile: '土壤状态',
    settings: '系统配置'
};


// 添加数据阈值配置
const thresholds = {
    moisture: { min: 35, max: 65 },  // 适宜的土壤含水量范围
    temperature: { min: 18, max: 28 },  // 适宜的土壤温度范围
    humidity: { min: 45, max: 65 },  // 适宜的湿度范围
    conductivity: { min: 100, max: 150 }  // 适宜的电导率范围
};

// 传感器数据结构
const sensors = [
    {
        id: 'sensor_1',
        name: '传感器 1',
        depth: 10,
        status: 'active',
        lastUpdate: new Date(),
        type: 'TDR',
        location: '测点 A',
        installDate: '2024-01-15'
    },
    {
        id: 'sensor_2',
        name: '传感器 2',
        depth: 20,
        status: 'active',
        lastUpdate: new Date(),
        type: 'FDR',
        location: '测点 B',
        installDate: '2024-01-15'
    }
];

document.addEventListener('DOMContentLoaded', function() {
    // 初始化实时监测页面
    initializeRealTimeChart();
    initializeChartSwitcher();
    initializeDataOverview();
    setupDepthSelector();
    setupConfigurationHandlers();
    startDataPolling();
    updateClock();
    setInterval(updateClock, 1000);
    
    // 设置实时监测为默认页面
    document.querySelector('.nav-link[data-page="realtime"]').classList.add('active');
    document.getElementById('realtimePage').style.display = 'block';
    
    // 立即显示实时数据图表
    showChart('realTimeView');
    updateAllCharts();
    
    // 初始化页面导航
    initializePageNavigation();
    
    // 初始化导出数据按钮
    document.getElementById('exportData').addEventListener('click', exportMonitoringData);
    
    // 初始化传感器管理
    initializeSensorManagement();
    
    // 初始化历史数据页面
    initializeHistoryPage();
});

// 初始化实时图表
function initializeRealTimeChart() {
    const ctx = document.getElementById('realTimeChart').getContext('2d');
    realTimeChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '土壤墒情 (%)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1,
                    yAxisID: 'y'
                },
                {
                    label: '水势 (kPa)',
                    data: [],
                    borderColor: 'rgb(255, 159, 64)',
                    borderWidth: 2,
                    tension: 0.1,
                    yAxisID: 'y1',
                    hidden: false  // 确保水势曲线默认显示
                },
                {
                    label: '温度（°C）',
                    data: [],
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.1,
                    yAxisID: 'y2'
                },

                {
                    label: '湿度（%）',
                    data: [],
                    borderColor: 'rgb(54, 162, 235)',
                    tension: 0.1,
                    yAxisID: 'y3'
                },

                {
                    label: '电导率（μS/cm）',
                    data: [],
                    borderColor: 'rgb(153, 102, 255)',
                    tension: 0.1,
                    yAxisID: 'y4'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                title: {
                    display: true,
                    text: '实时监测数据',
                    padding: 20
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: '土壤墒情 (%)'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    min: -50,  // 设置水势的显示范围
                    max: 0,
                    ticks: {
                        stepSize: 10,
                        callback: function(value) {
                            return value + ' kPa';
                        }
                    },
                    title: {
                        display: true,
                        text: '水势 (kPa)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y2: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '温度 (°C)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y3: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '湿度 (%)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y4: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '电导率 (μS/cm)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
}

// 修改数据概览面板初始化函数
function initializeDataOverview() {
    const overview = document.getElementById('dataOverview');
    overview.innerHTML = `
        <div class="data-overview-header">
            <h6 class="mb-2">当前深度: <span class="depth-value">${sensorConfig.currentDepth}cm</span></h6>
            <div class="update-time">更新时间: <span id="last-update-time">--</span></div>
        </div>
        <div class="data-grid">
            <div class="data-item">
                <div class="data-header">
                    <i class="fas fa-seedling text-success"></i>
                    <span>土壤墒情</span>
                </div>
                <div class="data-content">
                    <div class="main-value" id="moisture-value">--</div>
                 
                </div>
            </div>
            <div class="data-item">
                <div class="data-header">
                    <i class="fas fa-tint text-primary"></i>
                    <span>水势</span>
                </div>
                <div class="data-content">
                    <div class="main-value" id="water-potential-value">--</div>
                    
                </div>
            </div>
            <div class="data-item">
                <div class="data-header">
                    <i class="fas fa-thermometer-half text-danger"></i>
                    <span>温度</span>
                </div>
                <div class="data-content">
                    <div class="main-value" id="temperature-value">--</div>
                   
                </div>
            </div>
            <div class="data-item">
                <div class="data-header">
                    <i class="fas fa-cloud text-info"></i>
                    <span>湿度</span>
                </div>
                <div class="data-content">
                    <div class="main-value" id="humidity-value">--</div>
                  
                </div>
            </div>
            <div class="data-item">
                <div class="data-header">
                    <i class="fas fa-bolt text-warning"></i>
                    <span>电导率</span>
                </div>
                <div class="data-content">
                    <div class="main-value" id="conductivity-value">--</div>
                    
                </div>
            </div>
        </div>
    `;
}

// 修改深度选择器处理函数
function setupDepthSelector() {
    const depthSelector = document.getElementById('depthSelector');
    depthSelector.addEventListener('click', function(e) {
        if (e.target.dataset.depth) {
            // 更新按钮状态
            depthSelector.querySelectorAll('button').forEach(btn => {
                btn.classList.remove('active');
            });
            e.target.classList.add('active');
            
            // 更新当前深度
            sensorConfig.currentDepth = parseInt(e.target.dataset.depth);
            
            // 更新所有图表
            updateAllCharts();
        }
    });
}

// 添加更新所有图表的函数
function updateAllCharts() {
    // 获取当前显示的图表类型
    const activeChartType = document.querySelector('[data-chart].active').dataset.chart;
    
    // 更新实时数据图表
    if (realTimeChart) {
        const currentData = depthData[sensorConfig.currentDepth];
        updateChartData({
            timestamp: new Date(),
            moisture: currentData.moisture[currentData.moisture.length - 1],
            temperature: currentData.temperature[currentData.temperature.length - 1],
            humidity: currentData.humidity[currentData.humidity.length - 1],
            conductivity: currentData.conductivity[currentData.conductivity.length - 1]
        });
    }
    
    // 更新24小时图表
    if (dayChart && activeChartType === '24h') {
        updateDayChart();
    }
    
    // 更新剖面图
    if (profileChart && activeChartType === 'profile') {
        updateProfileChart();
    }
    
    // 更新数据概览面板
    const currentData = depthData[sensorConfig.currentDepth];
    if (currentData.moisture.length > 0) {
        updateDataOverview({
            moisture: currentData.moisture[currentData.moisture.length - 1],
            waterPotential: currentData.waterPotential[currentData.waterPotential.length - 1],
            temperature: currentData.temperature[currentData.temperature.length - 1],
            humidity: currentData.humidity[currentData.humidity.length - 1],
            conductivity: currentData.conductivity[currentData.conductivity.length - 1]
        });
    }
}

// 添加配置处理
function setupConfigurationHandlers() {
    document.getElementById('samplingRate').addEventListener('change', (e) => {
        sensorConfig.samplingRate = parseInt(e.target.value);
        restartDataPolling();
    });

    document.getElementById('dataRetention').addEventListener('change', (e) => {
        sensorConfig.dataRetention = parseInt(e.target.value);
    });
}

// 修改数据获取函数
async function fetchSensorData() {
    // 基准值设置（模拟真实环境的合理数据）
    const baseValues = {
        moisture: {
            base: 45,  // 基准土壤含水量 45%
            variation: 5,  // 波动范围 ±5%
            depthEffect: 0.8  // 深度影响因子
        },
        waterPotential: {
            base: -33,  // 基准水势 -33kPa
            variation: 3,
            depthEffect: 1.2
        },
        temperature: {
            base: 22,  // 基准温度 22°C
            variation: 1.5,
            depthEffect: 0.95  // 深度越大温度变化越小
        },
        humidity: {
            base: 55,  // 基准湿度 55%
            variation: 3,
            depthEffect: 0.9
        },
        conductivity: {
            base: 120,  // 基准电导率 120μS/cm
            variation: 10,
            depthEffect: 1.1
        }
    };

    const data = {};
    sensorConfig.depths.forEach(depth => {
        // 计算深度影响
        const depthFactor = depth / 100;  // 将深度转换为比例因子
        
        // 为每个参数生成考虑深度影响的随机值
        const moistureValue = baseValues.moisture.base + 
            (Math.random() * 2 - 1) * baseValues.moisture.variation * 
            Math.pow(baseValues.moisture.depthEffect, depthFactor);
        
        const waterPotentialValue = baseValues.waterPotential.base + 
            (Math.random() * 2 - 1) * baseValues.waterPotential.variation * 
            Math.pow(baseValues.waterPotential.depthEffect, depthFactor);
        
        const temperatureValue = baseValues.temperature.base + 
            (Math.random() * 2 - 1) * baseValues.temperature.variation * 
            Math.pow(baseValues.temperature.depthEffect, depthFactor);
        
        const humidityValue = baseValues.humidity.base + 
            (Math.random() * 2 - 1) * baseValues.humidity.variation * 
            Math.pow(baseValues.humidity.depthEffect, depthFactor);
        
        const conductivityValue = baseValues.conductivity.base + 
            (Math.random() * 2 - 1) * baseValues.conductivity.variation * 
            Math.pow(baseValues.conductivity.depthEffect, depthFactor);

        data[depth] = {
            timestamp: new Date(),
            moisture: Math.max(0, Math.min(100, moistureValue)),
            waterPotential: waterPotentialValue,
            temperature: temperatureValue,
            humidity: Math.max(0, Math.min(100, humidityValue)),
            conductivity: Math.max(0, conductivityValue)
        };
    });
    return data;
}

// 更新图表数据
function updateChartData(data) {
    const maxDataPoints = 60; // 显示最近60个数据点
    
    if (realTimeChart.data.labels.length > maxDataPoints) {
        realTimeChart.data.labels.shift();
        realTimeChart.data.datasets.forEach(dataset => dataset.data.shift());
    }
    
    // 生成水势数据，范围在-50到0之间，并保持平滑变化
    const lastWaterPotential = realTimeChart.data.datasets[1].data.length > 0 
        ? realTimeChart.data.datasets[1].data[realTimeChart.data.datasets[1].data.length - 1] 
        : -30;
    
    // 添加小幅随机波动，但保持平滑变化
    const waterPotentialChange = (Math.random() - 0.5) * 2; // 每次变化±1kPa
    const newWaterPotential = Math.max(-50, Math.min(0, lastWaterPotential + waterPotentialChange));
    
    realTimeChart.data.labels.push(new Date().toLocaleTimeString());
    realTimeChart.data.datasets[0].data.push(data.moisture);
    realTimeChart.data.datasets[1].data.push(newWaterPotential);
    realTimeChart.data.datasets[2].data.push(data.temperature);
    realTimeChart.data.datasets[3].data.push(data.humidity);
    realTimeChart.data.datasets[4].data.push(data.conductivity);
    
    realTimeChart.update('none');
}

// 添加数据检查函数
function checkDataThresholds(data) {
    const warnings = [];
    
    if (data.moisture < thresholds.moisture.min || data.moisture > thresholds.moisture.max) {
        warnings.push(`土壤墒情异常: ${data.moisture.toFixed(1)}%`);
    }
    if (data.temperature < thresholds.temperature.min || data.temperature > thresholds.temperature.max) {
        warnings.push(`温度异常: ${data.temperature.toFixed(1)}°C`);
    }
    if (data.humidity < thresholds.humidity.min || data.humidity > thresholds.humidity.max) {
        warnings.push(`湿度异常: ${data.humidity.toFixed(1)}%`);
    }
    if (data.conductivity < thresholds.conductivity.min || data.conductivity > thresholds.conductivity.max) {
        warnings.push(`电导率异常: ${data.conductivity.toFixed(1)} μS/cm`);
    }
    
    return warnings;
}

// 添加趋势计算函数
function calculateTrend(data, count = 5) {
    if (data.length < 2) return 0;
    
    // 获取最近的几个数据点
    const recentData = data.slice(-count);
    
    // 计算变化率
    const firstValue = recentData[0];
    const lastValue = recentData[recentData.length - 1];
    const changeRate = ((lastValue - firstValue) / firstValue) * 100;
    
    return changeRate;
}

// 添加趋势显示函数
function getTrendDisplay(trend) {
    if (Math.abs(trend) < 0.5) {
        return '<i class="fas fa-minus text-secondary"></i> 稳定';
    } else if (trend > 0) {
        return '<i class="fas fa-arrow-up text-danger"></i> 上升';
    } else {
        return '<i class="fas fa-arrow-down text-success"></i> 下降';
    }
}

// 修改数据概览更新函数
function updateDataOverview(data) {
    // 获取当前深度的数据
    const currentDepth = sensorConfig.currentDepth;
    const depthDataSet = depthData[currentDepth];
    
    // 计算各参数的趋势
    const moistureTrend = calculateTrend(depthDataSet.moisture);
    const waterPotentialTrend = calculateTrend(depthDataSet.waterPotential);
    const temperatureTrend = calculateTrend(depthDataSet.temperature);
    const humidityTrend = calculateTrend(depthDataSet.humidity);
    const conductivityTrend = calculateTrend(depthDataSet.conductivity);

    // 计算日均值（这里使用模拟数据，实际应从后端获取）
    const avgData = {
        moisture: (data.moisture * 0.95).toFixed(2),
        waterPotential: (data.waterPotential * 0.98).toFixed(2),
        temperature: (data.temperature * 0.97).toFixed(2),
        humidity: (data.humidity * 0.96).toFixed(2),
        conductivity: (data.conductivity * 0.99).toFixed(2)
    };

    // 更新当前值
    document.getElementById('moisture-value').textContent = `${data.moisture.toFixed(2)}%`;
    document.getElementById('water-potential-value').textContent = `${data.waterPotential.toFixed(2)} kPa`;
    document.getElementById('temperature-value').textContent = `${data.temperature.toFixed(2)}°C`;
    document.getElementById('humidity-value').textContent = `${data.humidity.toFixed(2)}%`;
    document.getElementById('conductivity-value').textContent = `${data.conductivity.toFixed(2)} μS/cm`;

    // 更新日均值
    document.getElementById('moisture-avg').textContent = `${avgData.moisture}%`;
    document.getElementById('water-potential-avg').textContent = `${avgData.waterPotential} kPa`;
    document.getElementById('temperature-avg').textContent = `${avgData.temperature}°C`;
    document.getElementById('humidity-avg').textContent = `${avgData.humidity}%`;
    document.getElementById('conductivity-avg').textContent = `${avgData.conductivity} μS/cm`;

    // 更新趋势显示
    document.getElementById('moisture-trend').innerHTML = getTrendDisplay(moistureTrend);
    document.getElementById('water-potential-trend').innerHTML = getTrendDisplay(waterPotentialTrend);
    document.getElementById('temperature-trend').innerHTML = getTrendDisplay(temperatureTrend);
    document.getElementById('humidity-trend').innerHTML = getTrendDisplay(humidityTrend);
    document.getElementById('conductivity-trend').innerHTML = getTrendDisplay(conductivityTrend);

    // 更新最后更新时间
    document.getElementById('last-update-time').textContent = new Date().toLocaleTimeString();

    // 检查数据异常
    const warnings = checkDataThresholds(data);
    if (warnings.length > 0) {
        showWarnings(warnings);
    }
}

// 修改警告显示函数
function showWarnings(warnings) {
    // 只在实时监测页面显示警告
    if (document.querySelector('.nav-link[data-page="realtime"]').classList.contains('active')) {
        const warningContainer = document.getElementById('warningContainer');
        const warningList = document.getElementById('warningList');
        const warningCount = document.getElementById('warningCount');
        
        // 添加新的警告
        warnings.forEach(warning => {
            const warningItem = document.createElement('div');
            warningItem.className = 'warning-item';
            warningItem.innerHTML = `
                <div class="warning-time">${new Date().toLocaleTimeString()}</div>
                <div class="warning-text">${warning}</div>
            `;
            
            // 添加到列表开头
            warningList.insertBefore(warningItem, warningList.firstChild);
            
            // 限制最大显示数量
            if (warningList.children.length > 10) {
                warningList.removeChild(warningList.lastChild);
            }
        });
        
        // 更新警告数量
        warningCount.textContent = warningList.children.length;
        
        // 显示警告容器
        warningContainer.classList.add('show');
    }
}

// 添加清除警告函数
function clearWarnings() {
    const warningList = document.getElementById('warningList');
    const warningCount = document.getElementById('warningCount');
    warningList.innerHTML = '';
    warningCount.textContent = '0';
}

// 修改数据轮询函数
function startDataPolling() {
    if (window.pollingInterval) {
        clearInterval(window.pollingInterval);
    }
    window.pollingInterval = setInterval(async () => {
        const data = await fetchSensorData();
        // 更新所有深度的数据
        Object.entries(data).forEach(([depth, values]) => {
            updateDepthData(parseInt(depth), values);
        });
        // 更新卡片显示
        updateCardValues(data[sensorConfig.currentDepth]);
        // 更新其他图表
        updateAllCharts();
    }, sensorConfig.samplingRate);
}

// 添加数据存储函数
function updateDepthData(depth, data) {
    const maxDataPoints = (sensorConfig.dataRetention * 60 * 1000) / sensorConfig.samplingRate;
    
    Object.entries(data).forEach(([key, value]) => {
        if (key !== 'timestamp' && depthData[depth][key]) {
            depthData[depth][key].push(value);
            if (depthData[depth][key].length > maxDataPoints) {
                depthData[depth][key].shift();
            }
        }
    });
}

// 添加重启数据轮询函数
function restartDataPolling() {
    if (window.pollingInterval) {
        clearInterval(window.pollingInterval);
    }
    startDataPolling();
}

// 添加时钟显示功能
function updateClock() {
    const now = new Date();
    // 转换为北京时间
    const beijingTime = new Date(now.getTime() + (now.getTimezoneOffset() + 480) * 60000);
    
    // 格式化日期和时间
    const dateStr = beijingTime.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
    
    const timeStr = beijingTime.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    
    // 组合显示
    document.getElementById('currentTime').textContent = 
        `${dateStr} ${timeStr}`;
}

// 初始化页面切换功能
function initializePageNavigation() {
    // 为导航链接添加点击事件
    document.querySelectorAll('.nav-link[data-page]').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const pageId = e.target.closest('.nav-link').dataset.page;
            switchPage(pageId);
        });
    });
}

// 切换页面函数
function switchPage(pageId) {
    // 更新导航状态
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
    });
    document.querySelector(`.nav-link[data-page="${pageId}"]`).classList.add('active');

    // 隐藏所有页面
    Object.values(pages).forEach(id => {
        document.getElementById(id).style.display = 'none';
    });

    // 显示选中的页面
    document.getElementById(pages[pageId]).style.display = 'block';

    // 更新页面标题
    document.getElementById('pageTitle').textContent = pageTitles[pageId];

    // 更新页面工具栏
    updatePageTools(pageId);

    // 处理警告容器的显示/隐藏
    const warningContainer = document.getElementById('warningContainer');
    if (pageId === 'realtime') {
        warningContainer.style.display = 'block';
        if (realTimeChart) {
            updateAllCharts();
        }
    } else {
        warningContainer.style.display = 'none';
    }

    // 根据页面类型执行特定初始化
    switch(pageId) {
        case 'realtime':
            initializeRealTimeData();
            // 停止剖面数据轮询
            if (window.profilePollingInterval) {
                clearInterval(window.profilePollingInterval);
            }
            break;
        case 'history':
            initializeHistoryData();
            break;
        case 'profile':
            initializeSoilProfilePage();
            break;
        case 'settings':
            initializeSettings();
            break;
    }
}

// 添加页面工具栏更新函数
function updatePageTools(pageId) {
    const pageTools = document.querySelector('.page-tools');
    const exportBtn = document.getElementById('exportData');
    
    // 确保工具栏存在
    if (!pageTools) return;
    
    // 根据页面类型显示/隐藏导出按钮
    if (pageId === 'realtime') {
        exportBtn.style.display = 'inline-block';
        exportBtn.onclick = exportRealtimeData;
    } else {
        exportBtn.style.display = 'none';
    }
    
    // 显示工具栏
    pageTools.style.display = 'block';
}

// 完善实时数据页面初始化函数
function initializeRealTimeData() {
    if (!realTimeChart) {
        initializeRealTimeChart();
    }
    
    // 更新深度选择器状态
    const depthSelector = document.getElementById('depthSelector');
    depthSelector.querySelector(`button[data-depth="${sensorConfig.currentDepth}"]`).click();
}

// 添加历史数据页面初始化函数
function initializeHistoryData() {
    // 设置日期选择器的默认值
    const today = new Date();
    const startDate = document.getElementById('startDate');
    const endDate = document.getElementById('endDate');
    
    // 设置结束日期为今天
    endDate.value = today.toISOString().split('T')[0];
    // 设置开始日期为7天前
    const weekAgo = new Date(today);
    weekAgo.setDate(weekAgo.getDate() - 7);
    startDate.value = weekAgo.toISOString().split('T')[0];
    
    // 初始化历史数据图表
    if (!window.historyChart) {
        initializeHistoryChart();
    }
    
    // 添加时间范围按钮事件处理
    document.querySelectorAll('.query-tools .btn-group button').forEach(btn => {
        btn.addEventListener('click', (e) => {
            // 更新按钮状态
            document.querySelectorAll('.query-tools .btn-group button').forEach(b => 
                b.classList.remove('active'));
            e.target.classList.add('active');
            
            // 设置对应的日期范围
            const period = e.target.dataset.period;
            setDateRange(period);
        });
    });
    
    // 初始查询数据
    queryHistoryData();
}

// 添加设置日期范围函数
function setDateRange(period) {
    const endDate = new Date();
    const startDate = new Date();
    
    switch(period) {
        case 'day':
            startDate.setDate(endDate.getDate() - 1);
            break;
        case 'week':
            startDate.setDate(endDate.getDate() - 7);
            break;
        case 'month':
            startDate.setMonth(endDate.getMonth() - 1);
            break;
    }
    
    document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
    document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
    
    // 自动触发查询
    queryHistoryData();
}

// 修改历史数据图表初始化函数
function initializeHistoryChart() {
    const ctx = document.getElementById('historyChart').getContext('2d');
    window.historyChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '土壤墒情 (%)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.3,
                    borderWidth: 2,
                    yAxisID: 'y'
                },
                {
                    label: '水势 (kPa)',
                    data: [],
                    borderColor: 'rgb(255, 159, 64)',
                    tension: 0.3,
                    borderWidth: 2,
                    yAxisID: 'y1'
                },
                {
                    label: '温度 (°C)',
                    data: [],
                    borderColor: 'rgb(255, 99, 132)',
                    tension: 0.3,
                    borderWidth: 2,
                    yAxisID: 'y2'
                },
                {
                    label: '湿度 (%)',
                    data: [],
                    borderColor: 'rgb(54, 162, 235)',
                    tension: 0.3,
                    borderWidth: 2,
                    yAxisID: 'y3'
                },
                {
                    label: '电导率 (μS/cm)',
                    data: [],
                    borderColor: 'rgb(153, 102, 255)',
                    tension: 0.3,
                    borderWidth: 2,
                    yAxisID: 'y4'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            height: 400,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                title: {
                    display: true,
                    text: '历史监测数据趋势',
                    padding: 20,
                    font: {
                        size: 16,
                        weight: 'bold'
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label = label.split(' ')[0] + ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y.toFixed(2);
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: '日期'
                    },
                    ticks: {
                        maxRotation: 45
                    }
                },
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    min: 0,
                    max: 100,
                    title: {
                        display: true,
                        text: '土壤墒情 (%)'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '水势 (kPa)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y2: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '温度 (°C)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y3: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '湿度 (%)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y4: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '电导率 (μS/cm)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
}

// 添加历史数据查询函数
function queryHistoryData() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const dataType = document.getElementById('dataType').value;
    
    // 验证日期输入
    if (!startDate || !endDate) {
        showToast('请选择查询日期范围', 'error');
        return;
    }
    
    // 显示图表容器
    document.getElementById('historyChart').style.display = 'block';
    document.getElementById('queryResultOverview').style.display = 'block';
    
    // 生成模拟数据
    const data = generateMockHistoryData(startDate, endDate);
    
    // 更新查询结果概览
    updateQueryOverview(data);
    
    // 更新统计表格
    updateStatisticsTable(data);
    
    // 更新历史数据图表
    updateHistoryChart(data, dataType);
}

// 修改生成模拟数据函数
function generateMockHistoryData(startDate, endDate) {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const data = {
        timestamps: [],
        moisture: [],
        waterPotential: [],
        temperature: [],
        humidity: [],
        conductivity: []
    };
    
    // 确保生成足够的数据点
    for(let date = new Date(start); date <= end; date.setHours(date.getHours() + 1)) {
        data.timestamps.push(new Date(date));
        
        // 生成带有日变化的模拟数据
        const hour = date.getHours();
        const dayFactor = Math.sin(hour * Math.PI / 12); // 日变化因子
        const randomFactor = Math.random() * 0.5; // 添加随机波动
        
        // 土壤墒情 (35-65%)
        data.moisture.push(50 + 5 * dayFactor + randomFactor * 5);
        
        // 水势 (-50-0 kPa)
        data.waterPotential.push(-25 + 10 * dayFactor + randomFactor * 10);
        
        // 温度 (18-28℃)
        data.temperature.push(23 + 3 * dayFactor + randomFactor * 2);
        
        // 湿度 (45-65%)
        data.humidity.push(55 + 5 * dayFactor + randomFactor * 4);
        
        // 电导率 (100-150 μS/cm)
        data.conductivity.push(125 + 10 * dayFactor + randomFactor * 8);
    }
    
    return data;
}

// 更新查询结果概览
function updateQueryOverview(data) {
    // 更新数据点数
    document.getElementById('dataPointCount').textContent = data.timestamps.length;
    
    // 更新采样间隔
    document.getElementById('samplingInterval').textContent = '1小时';
    
    // 计算异常数据点
    const abnormalCount = countAbnormalData(data);
    document.getElementById('abnormalCount').textContent = abnormalCount;
    
    // 计算数据完整率
    const integrity = ((data.timestamps.length - abnormalCount) / data.timestamps.length * 100).toFixed(1);
    document.getElementById('dataIntegrity').textContent = integrity + '%';
}

// 更新统计表格
function updateStatisticsTable(data) {
    const parameters = {
        moisture: { name: '土壤墒情', unit: '%' },
        waterPotential: { name: '水势', unit: 'kPa' },
        temperature: { name: '温度', unit: '°C' },
        humidity: { name: '湿度', unit: '%' },
        conductivity: { name: '电导率', unit: 'μS/cm' }
    };
    
    let html = '';
    for (const [key, param] of Object.entries(parameters)) {
        const values = data[key];
        const stats = calculateStats(values);
        
        html += `
            <tr>
                <td>${param.name}</td>
                <td>${stats.min.toFixed(1)} ${param.unit}</td>
                <td>${stats.max.toFixed(1)} ${param.unit}</td>
                <td>${stats.avg.toFixed(1)} ${param.unit}</td>
                <td>${stats.std.toFixed(2)} ${param.unit}</td>
            </tr>
        `;
    }
    
    document.getElementById('statisticsTable').innerHTML = html;
}

// 计算统计值
function calculateStats(values) {
    const min = Math.min(...values);
    const max = Math.max(...values);
    const avg = values.reduce((a, b) => a + b) / values.length;
    
    // 计算标准差
    const variance = values.reduce((a, b) => a + Math.pow(b - avg, 2), 0) / values.length;
    const std = Math.sqrt(variance);
    
    return { min, max, avg, std };
}

// 统计异常数据
function countAbnormalData(data) {
    let count = 0;
    
    // 检查每个参数的异常值
    for (const value of data.moisture) {
        if (value < thresholds.moisture.min || value > thresholds.moisture.max) count++;
    }
    for (const value of data.temperature) {
        if (value < thresholds.temperature.min || value > thresholds.temperature.max) count++;
    }
    // ... 其他参数的检查
    
    return count;
}

// 更新历史数据图表
function updateHistoryChart(data, dataType) {
    const ctx = document.getElementById('historyChart');
    if (!ctx) {
        console.error('找不到历史数据图表元素');
        return;
    }
    
    // 销毁现有图表
    if (window.historyChart) {
        window.historyChart.destroy();
    }
    
    // 准备图表数据
    const datasets = [];
    const labels = data.timestamps.map(t => formatDateTime(t));
    
    // 根据选择的数据类型添加数据集
    if (dataType === 'all' || dataType === 'moisture') {
        datasets.push({
            label: '土壤墒情 (%)',
            data: data.moisture,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
        });
    }
    if (dataType === 'all' || dataType === 'water') {
        datasets.push({
            label: '水势 (kPa)',
            data: data.waterPotential,
            borderColor: 'rgb(255, 159, 64)',
            tension: 0.1
        });
    }
    if (dataType === 'all' || dataType === 'temperature') {
        datasets.push({
            label: '温度 (°C)',
            data: data.temperature,
            borderColor: 'rgb(255, 99, 132)',
            tension: 0.1
        });
    }
    if (dataType === 'all' || dataType === 'humidity') {
        datasets.push({
            label: '湿度 (%)',
            data: data.humidity,
            borderColor: 'rgb(54, 162, 235)',
            tension: 0.1
        });
    }
    if (dataType === 'all' || dataType === 'conductivity') {
        datasets.push({
            label: '电导率 (μS/cm)',
            data: data.conductivity,
            borderColor: 'rgb(153, 102, 255)',
            tension: 0.1
        });
    }
    
    // 创建新图表
    window.historyChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: datasets
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: {
                duration: 0 // 禁用动画，使图表立即显示
            },
            plugins: {
                title: {
                    display: true,
                    text: '历史数据趋势'
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: '时间'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: '数值'
                    }
                }
            }
        }
    });
}

// 修改土壤剖面页面初始化函数
function initializeSoilProfilePage() {
    // 更新土壤数据表格
    updateSoilDataTable();
    
    // 更新数据分析和状态评估
    updateSoilAnalysis();
    
    // 启动定时更新
    if (window.profileUpdateInterval) {
        clearInterval(window.profileUpdateInterval);
    }
    window.profileUpdateInterval = setInterval(() => {
        updateSoilDataTable();
        updateSoilAnalysis();
    }, 5000);
}

// 添加土壤数据表格更新函数
function updateSoilDataTable() {
    const tableBody = document.getElementById('soilDataTable');
    let html = '';
    
    sensorConfig.depths.forEach(depth => {
        const data = {
            moisture: depthData[depth].moisture[depthData[depth].moisture.length - 1] || 0,
            waterPotential: depthData[depth].waterPotential[depthData[depth].waterPotential.length - 1] || 0,
            temperature: depthData[depth].temperature[depthData[depth].temperature.length - 1] || 0
        };
        
        // 判断土壤状态
        let status = '';
        let statusClass = '';
        if (data.moisture < 35) {
            status = '偏干';
            statusClass = 'alert';
        } else if (data.moisture > 65) {
            status = '偏湿';
            statusClass = 'warning';
        } else {
            status = '适宜';
            statusClass = 'good';
        }
        
        html += `
            <tr>
                <td>${depth}</td>
                <td>${data.moisture.toFixed(1)}</td>
                <td>${data.waterPotential.toFixed(1)}</td>
                <td>${data.temperature.toFixed(1)}</td>
                <td><span class="status-badge ${statusClass}">${status}</span></td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
}

// 添加土壤分析更新函数
function updateSoilAnalysis() {
    // 获取所有深度的数据
    const soilData = {};
    sensorConfig.depths.forEach(depth => {
        soilData[depth] = {
            moisture: depthData[depth].moisture[depthData[depth].moisture.length - 1] || 0,
            waterPotential: depthData[depth].waterPotential[depthData[depth].waterPotential.length - 1] || 0,
            temperature: depthData[depth].temperature[depthData[depth].temperature.length - 1] || 0
        };
    });
    
    // 计算平均墒情
    const avgMoisture = Object.values(soilData).reduce((sum, data) => sum + data.moisture, 0) / sensorConfig.depths.length;
    document.querySelector('.avg-moisture').textContent = avgMoisture.toFixed(1) + '%';
    
    // 计算水分均匀度
    const moistureValues = Object.values(soilData).map(data => data.moisture);
    const maxDiff = Math.max(...moistureValues) - Math.min(...moistureValues);
    const uniformity = 100 - (maxDiff / avgMoisture * 100);
    document.querySelector('.moisture-uniformity').textContent = uniformity.toFixed(1) + '%';
    
    // 分析垂直分布特征
    const moistureDistribution = document.querySelector('.moisture-distribution');
    if (maxDiff < 5) {
        moistureDistribution.textContent = '土壤水分垂直分布均匀，各层次含水量差异小于5%';
    } else {
        const topMoisture = soilData[10].moisture;
        const bottomMoisture = soilData[100].moisture;
        if (topMoisture > bottomMoisture) {
            moistureDistribution.textContent = '表层水分含量较高，呈现自上而下递减趋势';
        } else {
            moistureDistribution.textContent = '深层水分含量较高，呈现自上而下递增趋势';
        }
    }
    
    // 分析水分运移状况
    const infiltrationStatus = document.querySelector('.infiltration-status');
    const moistureGradient = (soilData[100].moisture - soilData[10].moisture) / 90; // 计算水分梯度
    if (Math.abs(moistureGradient) < 0.1) {
        infiltrationStatus.textContent = '水分运移状态稳定，垂直梯度较小';
    } else if (moistureGradient > 0) {
        infiltrationStatus.textContent = '存在明显的向下运移趋势，可能有深层渗漏风险';
    } else {
        infiltrationStatus.textContent = '存在向上运移趋势，可能受毛管作用影响';
    }
    
    // 分析变化趋势
    const trendData = calculateMoistureTrend();
    document.querySelector('.moisture-trend').textContent = trendData.description;
    document.querySelector('.moisture-trend-value').textContent = 
        trendData.trend === 'stable' ? '稳定' : 
        trendData.trend === 'increasing' ? '上升' : '下降';
    
    // 更新整体评估
    updateOverallStatus(soilData, trendData);
}

// 更新整体评估
function updateOverallStatus(soilData, trendData) {
    const statusValue = document.querySelector('.status-value');
    const statusDescription = document.querySelector('.status-description');
    const statusIndicator = document.querySelector('.status-indicator');
    const recommendationList = document.querySelector('.recommendation-list');
    
    const avgMoisture = Object.values(soilData).reduce((sum, data) => sum + data.moisture, 0) / sensorConfig.depths.length;
    const moistureValues = Object.values(soilData).map(data => data.moisture);
    const uniformity = 100 - ((Math.max(...moistureValues) - Math.min(...moistureValues)) / avgMoisture * 100);
    
    let status = '';
    let description = '';
    let recommendations = [];
    
    // 综合评估土壤状态
    if (avgMoisture < 35) {
        status = '水分不足';
        statusIndicator.className = 'status-indicator status-alert';
        description = `土壤整体偏干（平均墒情${avgMoisture.toFixed(1)}%），需要及时补充水分`;
        recommendations = [
            '建议进行适量灌溉，补充土壤水分',
            '可以采用覆盖措施减少水分蒸发',
            '考虑调整灌溉计划，增加灌溉频次'
        ];
    } else if (avgMoisture > 65) {
        status = '水分过量';
        statusIndicator.className = 'status-indicator status-warning';
        description = `土壤水分偏高（平均墒情${avgMoisture.toFixed(1)}%），需注意排水`;
        recommendations = [
            '建议暂停灌溉，等待土壤水分下降',
            '检查排水系统是否正常工作',
            '考虑增加土壤透气性的改良措施'
        ];
    } else {
        status = '水分适宜';
        statusIndicator.className = 'status-indicator status-good';
        description = `土壤水分状况良好（平均墒情${avgMoisture.toFixed(1)}%），适合作物生长`;
        recommendations = [
            '保持当前水分管理方案',
            '定期监测土壤水分变化',
            '根据天气情况适时调整灌溉计划'
        ];
    }
    
    // 更新显示
    statusValue.textContent = status;
    statusDescription.textContent = description;
    recommendationList.innerHTML = recommendations.map(item => `<li>${item}</li>`).join('');
}

function initializeSettings() {
    // 系统配置页面初始化逻辑
}

// 添加图表切换初始化
function initializeChartSwitcher() {
    const chartBtns = document.querySelectorAll('[data-chart]');
    chartBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const chartType = e.target.closest('[data-chart]').dataset.chart;
            switchChart(chartType);
        });
    });
    
    // 默认显示实时图表
    document.getElementById('realtimeBtn').classList.add('active', 'btn-primary');
    document.getElementById('realtimeBtn').classList.remove('btn-outline-primary');
}

// 图表切换函数
function switchChart(chartType) {
    // 更新按钮状态
    const buttons = document.querySelectorAll('[data-chart]');
    buttons.forEach(btn => {
        btn.classList.remove('active', 'btn-primary');
        btn.classList.add('btn-outline-primary');
    });
    
    const activeBtn = document.querySelector(`[data-chart="${chartType}"]`);
    activeBtn.classList.add('active', 'btn-primary');
    activeBtn.classList.remove('btn-outline-primary');

    // 隐藏所有图表
    const charts = document.querySelectorAll('.chart-view');
    charts.forEach(chart => {
        chart.classList.remove('active');
        chart.style.opacity = '0';
    });
    
    // 根据类型显示对应图表
    const showChart = (viewId) => {
        const view = document.getElementById(viewId);
        view.classList.add('active');
        // 使用延时确保过渡动画顺滑
        setTimeout(() => {
            view.style.opacity = '1';
        }, 50);
    };
    
    // 显示选中的图表
    switch(chartType) {
        case 'realtime':
            showChart('realTimeView');
            updateAllCharts();
            break;
        case '24h':
            showChart('dayView');
            if (!dayChart) {
                initializeDayChart();
            }
            updateAllCharts();
            break;
        case 'profile':
            showChart('profileView');
            if (!profileChart) {
                initializeProfileChart();
            }
            updateAllCharts();
            break;
    }
}

// 24小时图表初始化
function initializeDayChart() {
    const ctx = document.getElementById('dayChart').getContext('2d');
    dayChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '土壤墒情 (%)',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    fill: false,
                    borderWidth: 2,
                    yAxisID: 'y'
                },
                {
                    label: '水势 (kPa)',
                    data: [],
                    borderColor: 'rgb(54, 162, 235)',
                    fill: false,
                    borderWidth: 2,
                    yAxisID: 'y1'
                },
                {
                    label: '温度 (°C)',
                    data: [],
                    borderColor: 'rgb(255, 99, 132)',
                    fill: false,
                    borderWidth: 2,
                    yAxisID: 'y2'
                },
                {
                    label: '湿度 (%)',
                    data: [],
                    borderColor: 'rgb(255, 159, 64)',
                    fill: false,
                    borderWidth: 2,
                    yAxisID: 'y3'
                },
                {
                    label: '电导率 (μS/cm)',
                    data: [],
                    borderColor: 'rgb(153, 102, 255)',
                    fill: false,
                    borderWidth: 2,
                    yAxisID: 'y4'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                title: {
                    display: true,
                    text: '24小时监测数据趋势',
                    padding: 20,
                    font: {
                        size: 16,
                        weight: 'bold'
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label = label.split(' ')[0] + ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y.toFixed(2);
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                x: {
                    ticks: {
                        source: 'labels',
                        maxRotation: 0,
                        maxTicksLimit: 24,
                        autoSkip: true,
                        callback: function(value, index) {
                            return index % 2 === 0 ? value : '';
                        }
                    },
                    title: {
                        display: true,
                        text: '时间'
                    }
                },
                y: {
                    beginAtZero: true,
                    type: 'linear',
                    display: true,
                    position: 'left',
                    min: 0,
                    max: 100,
                    title: {
                        display: true,
                        text: '土壤墒情 (%)'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '水势 (kPa)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y2: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '温度 (°C)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y3: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '湿度 (%)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                },
                y4: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: '电导率 (μS/cm)'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
}

// 更新24小时图表数据
function updateDayChart() {
    const currentDepth = sensorConfig.currentDepth;
    // 生成时间标签（每小时一个点）
    const timeLabels = Array.from({length: 24}, (_, i) => {
        const hour = 23 - i;
        return `${hour.toString().padStart(2, '0')}:00`;
    }).reverse();
    
    dayChart.data.labels = timeLabels;
    
    // 生成模拟数据（实际项目中应该从后端获取）
    const generateHourlyData = (baseValue, variation) => {
        return Array.from({length: 24}, () => 
            baseValue + (Math.random() * 2 - 1) * variation
        );
    };

    // 使用模拟数据更新图表
    dayChart.data.datasets[0].data = generateHourlyData(45, 5);  // 墒情
    dayChart.data.datasets[1].data = generateHourlyData(-33, 3); // 水势
    dayChart.data.datasets[2].data = generateHourlyData(22, 2);  // 温度
    dayChart.data.datasets[3].data = generateHourlyData(55, 4);  // 湿度
    dayChart.data.datasets[4].data = generateHourlyData(120, 10); // 电导率
    
    dayChart.update('none');
}

// 修改剖面图表初始化函数
function initializeProfileChart() {
    const ctx = document.getElementById('profileChart').getContext('2d');
    profileChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: sensorConfig.depths,
            datasets: [
                {
                    label: '土壤墒情',
                    data: [],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.3,
                    borderWidth: 2,
                    pointRadius: 6,
                    pointBackgroundColor: 'rgb(75, 192, 192)',
                    pointBorderColor: '#fff',
                    pointHoverRadius: 8
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '土壤墒情剖面分布',
                    padding: 20,
                    font: {
                        size: 16,
                        weight: 'bold'
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `墒情: ${context.parsed.x.toFixed(1)}%`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    min: 0,
                    max: 100,
                    title: {
                        display: true,
                        text: '土壤墒情 (%)',
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)',
                            drawBorder: false
                        }
                    },
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)',
                        drawBorder: false
                    }
                },
                y: {
                    reverse: true,  // 反转Y轴，使深度从上到下增加
                    min: 0,  // 最小深度
                    max: 120,  // 稍大于最大深度，留出空间
                    offset: true,  // 确保刻度值不会被切断
                    ticks: {
                        // 只显示配置的深度值
                        callback: function(value) {
                            if (sensorConfig.depths.indexOf(value) !== -1) {
                                return value + ' cm';
                            }
                            return '';  // 返回空字符串不显示其他刻度
                        },
                        // 直接使用配置的深度值作为刻度
                        values: sensorConfig.depths,
                        font: {
                            weight: 'bold'
                        },
                        padding: 10
                    },
                    title: {
                        display: true,
                        text: '深度 (cm)',
                        font: {
                            weight: 'bold'
                        }
                    },
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)',
                        drawBorder: false,
                        lineWidth: 1
                    }
                }
            },
            indexAxis: 'y',  // 横向显示
            layout: {
                padding: {
                    right: 20  // 添加右侧padding，确保刻度值显示完整
                }
            }
        }
    });
}

// 修改剖面图表数据更新函数
function updateProfileChart() {
    // 获取所有深度的最新墒情数据
    const moistureData = sensorConfig.depths.map(depth => {
        const data = depthData[depth].moisture;
        return data.length > 0 ? data[data.length - 1] : 0;
    });
    
    profileChart.data.datasets[0].data = moistureData;
    
    // 更新点的样式，突出显示当前选中的深度
    profileChart.data.datasets[0].pointBackgroundColor = sensorConfig.depths.map(depth => 
        depth === sensorConfig.currentDepth ? '#ff6b6b' : 'rgb(75, 192, 192)'
    );
    profileChart.data.datasets[0].pointRadius = sensorConfig.depths.map(depth => 
        depth === sensorConfig.currentDepth ? 8 : 6
    );
    
    profileChart.update('none');
}

// 添加窗口大小变化时的图表重绘
window.addEventListener('resize', () => {
    if (realTimeChart) realTimeChart.resize();
    if (dayChart) dayChart.resize();
    if (profileChart) profileChart.resize();
});

// 添加导出数据函数
function exportMonitoringData() {
    // 获取当前深度的数据
    const currentDepth = sensorConfig.currentDepth;
    const data = depthData[currentDepth];
    
    // 创建CSV内容
    let csvContent = 'Time,Soil Moisture (%),Water Potential (kPa),Temperature (°C),Humidity (%),Conductivity (μS/cm)\n';
    
    // 获取时间戳数组
    const timestamps = Array.from({length: data.moisture.length}, (_, i) => {
        const now = new Date();
        return new Date(now - (data.moisture.length - 1 - i) * sensorConfig.samplingRate);
    });
    
    // 组合数据
    for (let i = 0; i < data.moisture.length; i++) {
        csvContent += `${timestamps[i].toLocaleString()},` +
            `${data.moisture[i].toFixed(2)},` +
            `${data.waterPotential[i].toFixed(2)},` +
            `${data.temperature[i].toFixed(2)},` +
            `${data.humidity[i].toFixed(2)},` +
            `${data.conductivity[i].toFixed(2)}\n`;
    }
    
    // 创建Blob对象
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    // 设置文件名（包含深度和时间信息）
    const now = new Date();
    const fileName = `soil_monitoring_${currentDepth}cm_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getDate().toString().padStart(2,'0')}_${now.getHours().toString().padStart(2,'0')}${now.getMinutes().toString().padStart(2,'0')}.csv`;
    
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.display = 'none';
    
    // 添加到文档并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    // 显示导出成功提示
    showExportSuccess();
}

// 添加导出成功提示函数
function showExportSuccess() {
    const toast = document.createElement('div');
    toast.className = 'export-toast';
    toast.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        数据导出成功
    `;
    
    document.body.appendChild(toast);
    
    // 添加显示类
    setTimeout(() => toast.classList.add('show'), 100);
    
    // 3秒后移除
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
    }, 3000);
}

// 修改数据更新函数
function updateCardValues(data) {
    // 更新卡片数值
    document.getElementById('moisture-card-value').textContent = data.moisture.toFixed(1);
    document.getElementById('water-potential-card-value').textContent = data.waterPotential.toFixed(1);
    document.getElementById('temperature-card-value').textContent = data.temperature.toFixed(1);
    document.getElementById('humidity-card-value').textContent = data.humidity.toFixed(1);
    document.getElementById('conductivity-card-value').textContent = data.conductivity.toFixed(1);
    
    // 更新趋势指示器
    updateTrendIndicator('moisture', data.moisture);
    updateTrendIndicator('water-potential', data.waterPotential);
    updateTrendIndicator('temperature', data.temperature);
    updateTrendIndicator('humidity', data.humidity);
    updateTrendIndicator('conductivity', data.conductivity);
}

// 添加趋势指示器更新函数
function updateTrendIndicator(type, currentValue) {
    const trendElement = document.getElementById(`${type}-card-trend`);
    const previousValue = parseFloat(document.getElementById(`${type}-card-value`).textContent) || currentValue;
    
    let trendHtml = '';
    if (Math.abs(currentValue - previousValue) < 0.5) {
        trendHtml = '<i class="fas fa-minus trend-stable"></i>';
    } else if (currentValue > previousValue) {
        trendHtml = '<i class="fas fa-arrow-up trend-up"></i>';
    } else {
        trendHtml = '<i class="fas fa-arrow-down trend-down"></i>';
    }
    
    trendElement.innerHTML = trendHtml;
}

// 添加水分趋势计算函数
function calculateMoistureTrend() {
    const recentData = {};
    sensorConfig.depths.forEach(depth => {
        recentData[depth] = depthData[depth].moisture.slice(-6); // 取最近6个数据点
    });

    let trend = 'stable';
    let description = '';

    // 计算变化率
    const changes = {};
    Object.entries(recentData).forEach(([depth, data]) => {
        if (data.length >= 2) {
            changes[depth] = ((data[data.length - 1] - data[0]) / data[0]) * 100;
        }
    });

    // 判断趋势
    const avgChange = Object.values(changes).reduce((sum, change) => sum + change, 0) / Object.keys(changes).length;
    if (Math.abs(avgChange) < 1) {
        trend = 'stable';
        description = '土壤水分保持稳定';
    } else if (avgChange > 1) {
        trend = 'increasing';
        description = '土壤水分呈增加趋势，增速约' + avgChange.toFixed(1) + '%';
    } else {
        trend = 'decreasing';
        description = '土壤水分呈减少趋势，降速约' + Math.abs(avgChange).toFixed(1) + '%';
    }

    return { trend, description };
}

// 初始化传感器管理
function initializeSensorManagement() {
    // 更新传感器列表
    updateSensorList();
    
    // 添加事件监听
    document.getElementById('addSensorBtn').addEventListener('click', showAddSensorModal);
    document.getElementById('sensorSearch').addEventListener('input', filterSensors);
    document.getElementById('sensorStatusFilter').addEventListener('change', filterSensors);
    
    // 更新传感器统计
    updateSensorStats();
}

// 更新传感器列表
function updateSensorList() {
    const sensorItems = document.getElementById('sensorItems');
    let html = '';
    
    sensors.forEach(sensor => {
        const lastUpdateTime = formatDateTime(sensor.lastUpdate);
        html += `
            <div class="sensor-item ${sensor.status}" data-id="${sensor.id}">
                <div class="sensor-header">
                    <div class="sensor-title">
                        <span class="sensor-status ${sensor.status}"></span>
                        ${sensor.name}
                    </div>
                    <div class="sensor-actions">
                        <button class="btn btn-sm btn-outline-primary" onclick="editSensor('${sensor.id}')">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteSensor('${sensor.id}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="sensor-info">
                    <div class="sensor-info-item">
                        <span class="sensor-info-label">深度:</span>
                        <span class="sensor-info-value">${sensor.depth} cm</span>
                    </div>
                    <div class="sensor-info-item">
                        <span class="sensor-info-label">类型:</span>
                        <span class="sensor-info-value">${sensor.type}</span>
                    </div>
                    <div class="sensor-info-item">
                        <span class="sensor-info-label">位置:</span>
                        <span class="sensor-info-value">${sensor.location}</span>
                    </div>
                    <div class="sensor-info-item">
                        <span class="sensor-info-label">最后更新:</span>
                        <span class="sensor-info-value">${lastUpdateTime}</span>
                    </div>
                </div>
            </div>
        `;
    });
    
    sensorItems.innerHTML = html;
}

// 更新传感器统计
function updateSensorStats() {
    const totalSensors = sensors.length;
    const activeSensors = sensors.filter(s => s.status === 'active').length;
    const inactiveSensors = totalSensors - activeSensors;
    
    document.getElementById('totalSensors').textContent = totalSensors;
    document.getElementById('activeSensors').textContent = activeSensors;
    document.getElementById('inactiveSensors').textContent = inactiveSensors;
}

// 过滤传感器列表
function filterSensors() {
    const searchText = document.getElementById('sensorSearch').value.toLowerCase();
    const statusFilter = document.getElementById('sensorStatusFilter').value;
    const sensorItems = document.querySelectorAll('.sensor-item');
    
    sensorItems.forEach(item => {
        const sensor = sensors.find(s => s.id === item.dataset.id);
        const matchesSearch = sensor.name.toLowerCase().includes(searchText) ||
                            sensor.location.toLowerCase().includes(searchText);
        const matchesStatus = statusFilter === 'all' || sensor.status === statusFilter;
        
        item.style.display = matchesSearch && matchesStatus ? 'block' : 'none';
    });
}

// 修改添加传感器函数
function showAddSensorModal() {
    const modal = new bootstrap.Modal(document.getElementById('sensorModal'));
    // 重置表单
    document.getElementById('sensorForm').reset();
    document.getElementById('sensorId').value = '';
    document.getElementById('sensorModalTitle').textContent = '添加传感器';
    
    // 设置默认安装日期为今天
    document.getElementById('sensorInstallDate').value = new Date().toISOString().split('T')[0];
    
    // 添加保存按钮事件
    document.getElementById('saveSensorBtn').onclick = saveSensor;
    
    modal.show();
}

// 修改编辑传感器函数
function editSensor(sensorId) {
    const sensor = sensors.find(s => s.id === sensorId);
    if (!sensor) return;
    
    const modal = new bootstrap.Modal(document.getElementById('sensorModal'));
    document.getElementById('sensorModalTitle').textContent = '编辑传感器';
    
    // 填充表单数据
    document.getElementById('sensorId').value = sensor.id;
    document.getElementById('sensorName').value = sensor.name;
    document.getElementById('sensorDepth').value = sensor.depth;
    document.getElementById('sensorType').value = sensor.type;
    document.getElementById('sensorLocation').value = sensor.location;
    document.getElementById('sensorInstallDate').value = new Date(sensor.installDate).toISOString().split('T')[0];
    
    // 添加保存按钮事件
    document.getElementById('saveSensorBtn').onclick = saveSensor;
    
    modal.show();
}

// 添加保存传感器函数
function saveSensor() {
    const form = document.getElementById('sensorForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const sensorData = {
        id: document.getElementById('sensorId').value || 'sensor_' + (sensors.length + 1),
        name: document.getElementById('sensorName').value,
        depth: parseInt(document.getElementById('sensorDepth').value),
        type: document.getElementById('sensorType').value,
        location: document.getElementById('sensorLocation').value,
        installDate: document.getElementById('sensorInstallDate').value,
        status: 'active',
        lastUpdate: new Date()
    };
    
    // 更新或添加传感器
    const existingIndex = sensors.findIndex(s => s.id === sensorData.id);
    if (existingIndex !== -1) {
        sensors[existingIndex] = { ...sensors[existingIndex], ...sensorData };
    } else {
        sensors.push(sensorData);
    }
    
    // 更新界面
    updateSensorList();
    updateSensorStats();
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(document.getElementById('sensorModal'));
    modal.hide();
    
    // 显示成功提示
    showToast('传感器配置已保存');
}

// 添加提示框函数
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast-notification ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>
        ${message}
    `;
    
    document.body.appendChild(toast);
    setTimeout(() => toast.classList.add('show'), 100);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
    }, 3000);
}

// 格式化日期时间
function formatDateTime(date) {
    return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 初始化历史数据页面
function initializeHistoryPage() {
    // 设置默认日期范围
    const today = new Date();
    const weekAgo = new Date(today);
    weekAgo.setDate(today.getDate() - 7);
    
    document.getElementById('startDate').value = weekAgo.toISOString().split('T')[0];
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    
    // 添加查询按钮事件监听
    document.querySelector('.query-tools button[data-period="day"]').addEventListener('click', () => setQueryPeriod('day'));
    document.querySelector('.query-tools button[data-period="week"]').addEventListener('click', () => setQueryPeriod('week'));
    document.querySelector('.query-tools button[data-period="month"]').addEventListener('click', () => setQueryPeriod('month'));
    
    // 添加查询按钮事件监听
    document.querySelector('button.btn-primary[onclick="queryHistoryData()"]').addEventListener('click', queryHistoryData);
}

// 设置查询时间段
function setQueryPeriod(period) {
    const endDate = new Date();
    const startDate = new Date();
    
    switch(period) {
        case 'day':
            startDate.setDate(endDate.getDate() - 1);
            break;
        case 'week':
            startDate.setDate(endDate.getDate() - 7);
            break;
        case 'month':
            startDate.setMonth(endDate.getMonth() - 1);
            break;
    }
    
    // 更新日期输入框
    document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
    document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
    
    // 更新按钮状态
    document.querySelectorAll('.query-tools button').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`.query-tools button[data-period="${period}"]`).classList.add('active');
    
    // 自动触发查询
    queryHistoryData();
}

// 保留实时监测数据导出函数
function exportRealtimeData() {
    // 获取当前深度的数据
    const currentDepth = document.querySelector('#depthSelector button.active').dataset.depth;
    const data = depthData[currentDepth];
    
    // 创建CSV内容
    let csvContent = 'Time,Soil Moisture (%),Water Potential (kPa),Temperature (°C),Humidity (%),Conductivity (μS/cm)\n';
    
    // 获取时间戳数组
    const timestamps = Array.from({length: data.moisture.length}, (_, i) => {
        const now = new Date();
        return new Date(now - (data.moisture.length - 1 - i) * sensorConfig.samplingRate);
    });
    
    // 组合数据
    for (let i = 0; i < data.moisture.length; i++) {
        csvContent += `${timestamps[i].toLocaleString()},` +
            `${data.moisture[i].toFixed(2)},` +
            `${data.waterPotential[i].toFixed(2)},` +
            `${data.temperature[i].toFixed(2)},` +
            `${data.humidity[i].toFixed(2)},` +
            `${data.conductivity[i].toFixed(2)}\n`;
    }
    
    // 生成文件名
    const fileName = `realtime_monitoring_${currentDepth}cm_${formatDateForFileName(new Date())}.csv`;
    
    // 下载文件
    downloadCSV(csvContent, fileName);
}

// 保留辅助函数
function formatDateForFileName(date) {
    return `${date.getFullYear()}${(date.getMonth()+1).toString().padStart(2,'0')}${date.getDate().toString().padStart(2,'0')}_${date.getHours().toString().padStart(2,'0')}${date.getMinutes().toString().padStart(2,'0')}`;
}

function downloadCSV(csvContent, fileName) {
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    showToast('数据导出成功', 'success');
}

// 添加显示图表函数
function showChart(viewId) {
    const view = document.getElementById(viewId);
    if (!view) return;
    
    // 移除其他图表的活动状态
    document.querySelectorAll('.chart-view').forEach(chart => {
        chart.classList.remove('active');
        chart.style.opacity = '0';
    });
    
    // 显示选中的图表
    view.classList.add('active');
    view.style.opacity = '1';
    
    // 如果是实时图表，确保按钮状态正确
    if (viewId === 'realTimeView') {
        const realtimeBtn = document.getElementById('realtimeBtn');
        realtimeBtn.classList.add('active', 'btn-primary');
        realtimeBtn.classList.remove('btn-outline-primary');
    }
} 